export ZSH=${ZSH:-${HOME}/.oh-my-zsh}
export REMOTE=${REMOTE:-'https://gitee.com/mirrors/ohmyzsh.git'}
export BRANCH=${BRANCH:-master}

export CHSH=${CHSH:-yes}
export RUNZSH=${RUNZSH:-yes}
export KEEP_ZSHRC=${KEEP_ZSHRC:-no}
export HTTP_PROXY=${HTTP_PROXY:-http://192.168.31.31:7890}

echo "ZSH:        ${ZSH}"
echo "REMOTE:     ${REMOTE}"
echo "BRANCH:     ${BRANCH}"
echo "CHSH:       ${CHSH}"
echo "RUNZSH:     ${RUNZSH}"
echo "KEEP_ZSHRC: ${KEEP_ZSHRC}"
echo "HTTP_PROXY: ${HTTP_PROXY}"

RUNZSH=no KEEP_ZSHRC=no sh -c "$(curl -fsSL https://gitee.com/mirrors/ohmyzsh/raw/master/tools/install.sh)"

if [ "$KEEP_ZSHRC" = "no" ]; then
    echo "create .zshrc"
    cat >"$HOME/.zshrc" <<EOF
export ZSH="\$HOME/.oh-my-zsh"
ZSH_THEME="ys"
zstyle ':omz:update' mode disabled  # disable automatic updates
zstyle ':omz:update' frequency 180
plugins=(git golang docker docker-compose)
source \$ZSH/oh-my-zsh.sh
source \$HOME/.proxy.zsh
alias zv="vi ~/.zshrc"
alias zr="source ~/.zshrc"
alias cls=clear
EOF
fi

if [ -n "${HTTP_PROXY}" ]; then
    echo "create .proxy.zsh"
    cat >$HOME/.proxy.zsh <<EOF
export proxy=$HTTP_PROXY

gitProxySet() {
    if command -v git >/dev/null; then
        git config --global http.proxy \$http_proxy
    fi
}

gitProxyGet() {
    if command -v git >/dev/null; then
        echo "git_proxy=$(git config --global http.proxy)"
    fi
}

gitProxyUnset() {
    if command -v git >/dev/null; then
        git config --global --unset http.proxy
    fi
}

showp() {
    echo "http_proxy=\$http_proxy"
    echo "https_proxy=\$https_proxy"
    echo "all_proxy=\$all_proxy"
    echo "HTTP_PROXY=\$HTTP_PROXY"
    echo "HTTPS_PROXY=\$HTTPS_PROXY"
    echo "ALL_PROXY=\$ALL_PROXY"
    gitProxyGet
}

setp() {
    export http_proxy=\$proxy
    export https_proxy=\$proxy
    export all_proxy=\$proxy
    export HTTP_PROXY=\$proxy
    export HTTPS_PROXY=\$proxy
    export ALL_PROXY=\$proxy
    gitProxySet
    showp
}

usetp() {
    unset http_proxy
    unset https_proxy
    unset all_proxy
    unset HTTP_PROXY
    unset HTTPS_PROXY
    unset ALL_PROXY
    gitProxyUnset
    showp
}
EOF
fi

if [ "$CHSH" = "yes" ]; then
    echo "chsh"
    if command -v chsh >/dev/null; then
        if [ "$(id -u)" = "0" ]; then
            chsh -s $(command -v zsh)
        else
            sudo chsh -s $(command -v zsh)
        fi
    fi
fi

if [ "$RUNZSH" = "no" ]; then
    echo "Run zsh to try it out."
else
    echo "Run"
    exec zsh -l
fi
